package net.ustc.javamemcached.memorystore;

import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;

public class MemoryEntry {
	private int entrySize;
	
	private int keySize;
	private ChannelBuffer key;
	private int valueSize;
	private ChannelBuffer value;
	
	private long expireTime;
	private int flags;
	private long casUnique;
	
	private boolean isDirty; 
	
	public MemoryEntry(ChannelBuffer buffer){
		buffer.readerIndex(0);
		this.entrySize = buffer.readInt();
		this.keySize = buffer.readInt();
		this.key = buffer.readSlice(keySize);
		this.valueSize = buffer.readInt();
		this.value = buffer.readSlice(valueSize);
		this.expireTime = buffer.readLong();
		this.flags = buffer.readInt();
		this.casUnique = buffer.readLong();
		this.isDirty = buffer.readByte()==0?true:false;
	}
	
	public MemoryEntry(ChannelBuffer key, ChannelBuffer value, long expireTime, int flags){
		key.readerIndex(0);
		value.readerIndex(0);
		this.keySize = key.readableBytes();
		this.valueSize = value.readableBytes();
		this.entrySize = 4 + 4 + this.keySize + 4 + this.valueSize + 8 + 4 + 8 + 1;
		this.key = key;
		this.value = value;
		this.expireTime = expireTime;
		this.flags = flags;
		this.isDirty = true;
	}
	
	public ChannelBuffer toChannelBuffer(){
		ChannelBuffer buffer = ChannelBuffers.buffer(this.entrySize);
		buffer.writeInt(entrySize);
		buffer.writeInt(keySize);
		buffer.writeBytes(key.array());
		buffer.writeInt(valueSize);
		buffer.writeBytes(value.array());
		buffer.writeLong(expireTime);
		buffer.writeInt(flags);
		buffer.writeLong(casUnique);
		buffer.writeByte(isDirty?1:0);
		return buffer;
	}
	
	public int getEntrySize(){
		return this.entrySize;
	}
	
}
